package org.lhr.mina;

import java.net.InetSocketAddress;

import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class MinaClient extends IoHandlerAdapter {
	public static void main(String[] args) {
		NioSocketConnector connector = new NioSocketConnector();
		DefaultIoFilterChainBuilder chainBuilder = connector.getFilterChain();
		chainBuilder.addLast("myChain", new ProtocolCodecFilter(new TextLineCodecFactory()));
		// 设置客户端的消息处理器
		connector.setHandler(new MinaClient());
		// 连接到服务器
		ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", 60001));
		future.awaitUninterruptibly();
		future.getSession().getCloseFuture().awaitUninterruptibly();
		connector.dispose();
	}

	/**
	 * 接收到客户端发送的消息
	 */
	@Override
	public void messageReceived(IoSession session,
			Object message)

	throws Exception {
		String msg = (String) message;
		System.out.println("接收到服务器端消息:" + msg);
		// 回送消息给客户端
		//session.write(msg);
	}
}
